﻿using Microsoft.Extensions.DependencyInjection;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;

namespace Modules.App.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class AppDeviceRepository : Repository<AppDevice, DefaultDbContext>
    {
        public AppDeviceRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public AppDevice? GetAppDeviceByIdCard(string idCard)
        {
            Sql sql = Sql.Builder.Select("id").From("app_device").Where("use_id_card=@0", idCard);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public AppDevice? GetAppDeviceByAlias(string alias)
        {
            Sql sql = Sql.Builder.Select("id").From("app_device").Where("alias=@0", alias);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }

        public IEnumerable<AppDevice> GetDevicesByProjectId(int projectId)
        {
            Sql sql = Sql.Builder;
            sql.Select("c.id")
                .From("project_group_member as a");
            sql.InnerJoin("person as b").On("a.person_id = b.person_id");
            sql.InnerJoin("app_device as c").On("b.card_number=c.use_id_card");
            sql.Where("a.project_id=@0 and a.status=1", projectId);
            var ids= DbContext.Fetch<int>(sql);
            return PopulateEntitiesByEntityIds(ids);
        }
    }
}